package com.warm.androidstudy.http;

import com.warm.androidstudy.MyApplication;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

public class OkHttpUtil {

    private OkHttpClient okHttpClient;
    /**
     *连接超时时间
     */
    private long connectionTime = 10L;

    /**
     *写入超时时间
     */
    private long writeTime = 10L;
    /**
     * 读取超时时间
     */
    private long readTime = 30L;
//    // 缓存文件
//    private File cacheFile = File
    /**
     * 缓存文件大小
     */
    private long maxSize = 8 * 1024 * 1024;
    /**
     * OkHttpCache
     */
    private Cache cache;



    private static OkHttpUtil okHttpUtil;

    public static OkHttpUtil getInstance(){
        if (okHttpUtil==null){
            synchronized (OkHttpUtil.class){
                if (okHttpUtil ==null){
                    okHttpUtil = new OkHttpUtil();
                }
            }
        }

        return okHttpUtil;
    }

    public OkHttpClient getInitOkHttpClient(){
        Cache cache = new Cache(MyApplication.getInstance().getCacheDir(), maxSize);
        if (okHttpClient==null){
            okHttpClient = new OkHttpClient().newBuilder()
                    //设置超时时间
                    .connectTimeout(connectionTime, TimeUnit.SECONDS)
                    //设置读取超时时间
                    .readTimeout(readTime, TimeUnit.SECONDS)
                    //设置写入超时时间
                    .writeTimeout(writeTime, TimeUnit.SECONDS)
                    .cache(cache)
                    .addInterceptor(new HttpLoggingInterceptor())
                    .addInterceptor(new HeadIntercept())
                    .build();
        }
        return okHttpClient;
    }
}
